package org.jeecg.modules.htxincailiao.account.controller;

import java.util.*;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.CommonAPI;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.PasswordUtil;
import org.jeecg.common.util.RequestUtil;
import org.jeecg.common.util.SmartBeanUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.base.service.BaseCommonService;
import org.jeecg.modules.htxincailiao.account.domain.vo.HTEntrepreneurVo;
import org.jeecg.modules.htxincailiao.account.domain.vo.HTMerchantVO;
import org.jeecg.modules.htxincailiao.account.entity.HTAlliance;
import org.jeecg.modules.htxincailiao.account.entity.HTForumsExpert;
import org.jeecg.modules.htxincailiao.account.entity.HTMerchant;
import org.jeecg.modules.htxincailiao.account.entity.HTPlatformUser;
import org.jeecg.modules.htxincailiao.account.service.IHTAccountService;
import org.jeecg.modules.htxincailiao.account.service.IHTMerchantService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.htxincailiao.address.domain.vo.HTAddressVO;
import org.jeecg.modules.htxincailiao.address.entity.HTEnterpriseAddress;
import org.jeecg.modules.htxincailiao.address.service.IHTEnterpriseAddressService;
import org.jeecg.modules.htxincailiao.enterprise.entity.HTBusinessModelCategory;
import org.jeecg.modules.htxincailiao.enterprise.service.IHTBusinessModelCategoryService;
import org.jeecg.modules.htxincailiao.industry.entity.HTIndustryCategory;
import org.jeecg.modules.htxincailiao.industry.service.IHTIndustryCategoryService;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.entity.SysUserRole;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: ht_merchant
 * @Author: jeecg-boot
 * @Date: 2021-08-09
 * @Version: V1.0
 */
@Api(tags = "ht_merchant")
@RestController
@RequestMapping("/account/hTMerchant")
@Slf4j
public class HTMerchantController extends JeecgController<HTMerchant, IHTMerchantService> {
    @Resource
    private IHTMerchantService hTMerchantService;

    @Resource
    private IHTAccountService accountService;

    @Resource
    private IHTEnterpriseAddressService enterpriseAddressService;

    @Resource
    private IHTIndustryCategoryService industryCategoryService;

    @Resource
    private IHTBusinessModelCategoryService businessModelCategoryService;

    @Lazy
    @Resource
    private CommonAPI commonApi;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private BaseCommonService baseCommonService;

    /**
     * 分页列表查询
     *
     * @param hTMerchant
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "ht_merchant-分页列表查询")
    @ApiOperation(value = "ht_merchant-分页列表查询", notes = "ht_merchant-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(HTMerchant hTMerchant,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<HTMerchant> queryWrapper = QueryGenerator.initQueryWrapper(hTMerchant, req.getParameterMap());
        queryWrapper.orderByDesc("username");
        String token = req.getHeader("X-Access-Token");
        if (StringUtils.isNotBlank(token)) {
            String username =  JwtUtil.getUsername(token);
            Set<String> roleSet = commonApi.queryUserRoles(username);
            for (String str : roleSet) {
                if(str.equals("merchant")){
                    queryWrapper.eq("username",username);
                }
            }
        }
        Page<HTMerchant> page = new Page<>(pageNo, pageSize);
        IPage<HTMerchant> pageList = hTMerchantService.page(page, queryWrapper);


        List<HTMerchant> list = pageList.getRecords();
        for (HTMerchant merchant : list) {
            //System.out.printf("\n\n\n getEnterpriseAddressId: %s \n\n\n", JSONObject.toJSONString(merchant.getEnterpriseAddressId()));
            HTEnterpriseAddress address = enterpriseAddressService.getById(merchant.getEnterpriseAddressId());
            //System.out.printf("\n\n\n address: %s \n\n\n", JSONObject.toJSONString(address));
            if (oConvertUtils.isNotEmpty(address)) {
                merchant.setContactPerson(address.getContactPerson());
                merchant.setContactPhoneNumber(address.getPhoneNumber());
            }
            if (StringUtils.isBlank(token)) {
                merchant.setPhoneNumber("登录查看");
                merchant.setParticipant("登录查看");
                merchant.setEmail("登录查看");
                merchant.setEnterpriseAddressId("登录查看");
            }
        }

        return Result.OK(pageList);
    }

    /**
     * 分页列表查询
     *
     * @param hTMerchant
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "ht_merchant-分页列表查询")
    @ApiOperation(value = "ht_merchant-分页列表查询", notes = "ht_merchant-分页列表查询")
    @GetMapping(value = "/pc-home-list")
    public Result<?> queryPageEntrepreneurList(HTMerchant hTMerchant,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        Page<HTMerchant> page = new Page<>(pageNo, pageSize);
        IPage<HTEntrepreneurVo> pageList = hTMerchantService.queryPageEntrepreneurList(page, null);


        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param hTMerchant
     * @return
     */
    @AutoLog(value = "ht_merchant-添加")
    @ApiOperation(value = "ht_merchant-添加", notes = "ht_merchant-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody HTMerchant hTMerchant) {
        Result<HTMerchant> result = new Result<HTMerchant>();
        try{
            hTMerchantService.save(hTMerchant);
            //管理员新增企业后自动创建账号
            String selectedRoles = "1407876491735248897";
            SysUser user = new SysUser();
            user.setUsername(hTMerchant.getUsername());
            user.setShopId(hTMerchant.getId());
            user.setPhoneNumber(hTMerchant.getPhoneNumber());
            user.setRealname(hTMerchant.getEnterpriseName());
            if (org.apache.commons.lang3.StringUtils.isBlank(hTMerchant.getPassword())) {
                user.setPassword("123456");
            }else{
                user.setPassword(hTMerchant.getPassword());
            }
            String salt = oConvertUtils.randomGen(8);
            user.setSalt(salt);
            String passwordEncode = PasswordUtil.encrypt(user.getUsername(), user.getPassword(), salt);
            user.setPassword(passwordEncode);
            user.setStatus(1);
            user.setDelFlag(CommonConstant.DEL_FLAG_0);
            //用户表字段org_code不能在这里设置他的值
            user.setOrgCode(null);
            // 保存用户走一个service 保证事务
            sysUserService.saveUser(user, selectedRoles, null);
            baseCommonService.addLog("添加用户，username： " +user.getUsername() ,CommonConstant.LOG_TYPE_2, 2);
            result.success("添加成功！");
        }catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    /**
     * 编辑
     *
     * @param hTMerchant
     * @return
     */
    @AutoLog(value = "ht_merchant-编辑")
    @ApiOperation(value = "ht_merchant-编辑", notes = "ht_merchant-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody HTMerchant hTMerchant) {
        Result<HTMerchant> result = new Result<HTMerchant>();
        try{
            HTMerchant htMerchant = hTMerchantService.getById(hTMerchant.getId());
            String username = htMerchant.getUsername();//获取数据库中的用户名
            //通过用户名查找用户信息
            SysUser user = sysUserService.getUserByName(username);
            hTMerchantService.updateById(hTMerchant);
            if (user == null) {
                return result.success("编辑成功！");
            }
            //将修改的信息更新到用户账号中去
            String selectedRoles = "1407876491735248897";
            user.setUsername(hTMerchant.getUsername());
            user.setShopId(hTMerchant.getId());
            user.setPhoneNumber(hTMerchant.getPhoneNumber());
            user.setRealname(hTMerchant.getEnterpriseName());
            if (org.apache.commons.lang3.StringUtils.isBlank(hTMerchant.getPassword())) {
            }else{
                //修改了密码
                String salt = oConvertUtils.randomGen(8);
                user.setSalt(salt);
                user.setPassword(hTMerchant.getPassword());
                String passwordEncode = PasswordUtil.encrypt(user.getUsername(), user.getPassword(), salt);
                user.setPassword(passwordEncode);
            }
            user.setStatus(1);
            user.setDelFlag(CommonConstant.DEL_FLAG_0);
            //用户表字段org_code不能在这里设置他的值
            user.setOrgCode(null);
            // 保存用户走一个service 保证事务
            sysUserService.editUser(user, selectedRoles, null);
            baseCommonService.addLog("修改用户，username： " +user.getUsername() ,CommonConstant.LOG_TYPE_2, 2);
            result.success("编辑成功！");
        }catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "ht_merchant-通过id删除")
    @ApiOperation(value = "ht_merchant-通过id删除", notes = "ht_merchant-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        HTMerchant htMerchant = hTMerchantService.getById(id);
        String username = htMerchant.getUsername();//获取数据库中的用户名
        //通过用户名查找用户信息
        SysUser user = sysUserService.getUserByName(username);
        if(null != user){
            //删除用户信息
            sysUserService.delUserById(user.getId());
        }
        this.hTMerchantService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "ht_merchant-批量删除")
    @ApiOperation(value = "ht_merchant-批量删除", notes = "ht_merchant-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        List<String> userIdList = new ArrayList<>();
        for(String id : idList){
            HTMerchant htMerchant = hTMerchantService.getById(id);
            String username = htMerchant.getUsername();//获取数据库中的用户名
            //通过用户名查找用户信息
            SysUser user = sysUserService.getUserByName(username);
            if(null != user){
                userIdList.add(user.getId());
            }
        }
        if(userIdList.size() > 0){
            sysUserService.delUserByIds(userIdList);
        }
        this.hTMerchantService.removeByIds(idList);
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "ht_merchant-通过id查询")
    @ApiOperation(value = "ht_merchant-通过id查询", notes = "ht_merchant-通过id查询")
    @RequestMapping(value = "/queryById", method = {RequestMethod.GET, RequestMethod.POST})
    public Result<?> queryById(HttpServletRequest req, @RequestParam(name = "id", required = false) String id) {
        if (req.getMethod().equals("POST")) {
            String line = RequestUtil.getPostParam(req);
            if (oConvertUtils.isNotEmpty(line)) {
                HTMerchant hTMerchant = JSONObject.parseObject(line, HTMerchant.class);
                id = hTMerchant.getId();
            }
        }
        HTMerchant hTMerchant = hTMerchantService.getById(id);

        if (hTMerchant == null) {
            return Result.error("未找到对应数据");
        }
        HTMerchantVO merchantVO = SmartBeanUtil.copy(hTMerchant, HTMerchantVO.class);
        if (oConvertUtils.isNotEmpty(merchantVO.getEnterpriseAddressId())) {
            HTAddressVO addressVO = enterpriseAddressService.queryByAddressId(merchantVO.getEnterpriseAddressId());
            merchantVO.setAddress(addressVO);
        }

        if (oConvertUtils.isNotEmpty(merchantVO.getIndustryCategoryId())) {
            HTIndustryCategory industryCategory = industryCategoryService.getById(merchantVO.getIndustryCategoryId());
            merchantVO.setIndustryCategory(industryCategory);
        }

        if (oConvertUtils.isNotEmpty(merchantVO.getBusinessModelId())) {
            HTBusinessModelCategory businessModelCategory = businessModelCategoryService.getById(merchantVO.getBusinessModelId());
            merchantVO.setBusinessModel(businessModelCategory);
        }
        Page<HTMerchant> page = new Page<>(1, 999);
        IPage<HTEntrepreneurVo> pageList = hTMerchantService.queryPageEntrepreneurList(page, id);
        if (pageList.getTotal() > 0) {
            merchantVO.setEntrepreneurVoList(pageList.getRecords());
        } else {
            merchantVO.setEntrepreneurVoList(Collections.emptyList());
        }

        String token = req.getHeader("X-Access-Token");
        if (StringUtils.isBlank(token)) {
            merchantVO.setPhoneNumber("登录查看");
            merchantVO.setParticipant("登录查看");
            merchantVO.setEmail("登录查看");
            merchantVO.setEnterpriseAddressId("登录查看");
        }
        return Result.OK(merchantVO);
    }

    /**
     * 导出excel
     *
     * @param req
     * @param hTMerchant
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest req, HTMerchant hTMerchant) {
        QueryWrapper<HTMerchant> queryWrapper = QueryGenerator.initQueryWrapper(hTMerchant, req.getParameterMap());
        Page<HTMerchant> page = new Page<HTMerchant>(1, 99999999);
        IPage<HTMerchant> pageList = hTMerchantService.page(page, queryWrapper);

        List<HTMerchant> list = pageList.getRecords();
        for (HTMerchant merchant : list) {
            HTEnterpriseAddress address = enterpriseAddressService.getById(merchant.getEnterpriseAddressId());
            if (oConvertUtils.isNotEmpty(address)) {
                merchant.setContactPerson(address.getContactPerson());
                merchant.setContactPhoneNumber(address.getPhoneNumber());
            }
        }

        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "平台商户");
        mv.addObject(NormalExcelConstants.CLASS, HTMerchant.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("平台商户", "导出人：admin", "平台商户"));
        mv.addObject(NormalExcelConstants.DATA_LIST, list);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, HTMerchant.class);
    }

}
